<?php namespace App\Http\Controllers;
use App\Source;
use Illuminate\Support\Facades\Auth;
use Input;
use Excel;
use DB;
use Redirect;
use Illuminate\Http\Request;
use App\Pub;
use App\File;
use App\Follow;
use Illuminate\Contracts\Auth\Guard;
class SourcesController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Welcome Controller
	|--------------------------------------------------------------------------
	|
	| This controller renders the "marketing page" for the application and
	| is configured to only allow guests. Like most of the other sample
	| controllers, you are free to modify or remove it as you desire.
	|
	*/

	/**
	 * Create a new controller instance.
	 *
	 * @return void
	 */
    public $ACT;
    public $USER;
    protected $auth;
	public function __construct(Guard $auth)
	{
        $this->auth = $auth;
        $this->USER = Auth::user();
        $this->ACT = 'sources';
//		$this->middleware('auth');
	}

	/**
	 * Show the application welcome screen to the user.
	 *
	 * @return Response
	 */
	public function index()
	{



        $ACT = $this->ACT;
        if ($this->auth->check()) {


            $follows_count = Follow::where('user_id', $this->USER->id)->count();
            $follows_data = Follow::where('user_id', $this->USER->id)->get();
            if ($follows_count == 0) {
                $follows = array();
            } else {
                foreach ($follows_data as $follow) {
                    $follows[] = $follow->follow_user_id;
                }
            }

            $uid = $this->USER->id;
            $follow_sources = Source::whereHas('follow', function ($q) use ($uid) {
                $q->where('user_id', $uid);

            })->orderBy('created_at', 'DESC')->get();
        }else{
            $follows = array();
            $follow_sources = array();
        }


        $sources = Source::where('create_date', date('Ymd'))->orderBy('created_at', 'DESC')->get();


		return view('sources.index',compact('ACT','sources','follows','follow_sources'));
	}


    public function show($id)
    {
        //
        $ACT = $this->ACT;
        $source = Source::find($id);
        $content = unserialize($source->contents);
        return view('sources.show',compact('ACT','sources','content'));
    }

    /**
     * Show the form for editing the specified resource.
     * GET /mounts/{id}/edit
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        echo $id.'edit';
    }


    public function update($id)
    {
        echo $id.'update';
    }

    public function follow(){

        if (!$this->auth->check()) {
            echo 'unsignin';
        }else{

            $followcount = Follow::where('user_id',Auth::user()->id)->where('follow_user_id',Input::get('user_id'))->count();
            if($followcount > 0){
                Follow::where('user_id',Auth::user()->id)->where('follow_user_id',Input::get('user_id'))->delete();
                echo 'unfollow';
            }else{
                $follow = new Follow();
                $follow->user_id = Auth::user()->id;
                $follow->follow_user_id = Input::get('user_id');
                $follow->save();
                echo 'follow';
            }

        }

    }

    public function download($id){
        $source = Source::find($id);
        $source->download = $source->download+1;
        $source->save();
        $pub = Pub::find(1);
        $path = $pub->path.$source->file->key;
        header("Location: ".$path);
//        Redirect::to('http://www.baidu.com/');
    }
    /**
     * Remove the specified resource from storage.
     * DELETE /mounts/{id}
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
    public function upload(){
        $ACT = $this->ACT;
        return view('sources.upload',compact('ACT'));
    }
    public function post_upload(Request $request){



//        $file = $request::file('file');
//        if ($request::hasFile('file'))
//        {
            //
//            var_dump(Input::file('file')->getFilename());
            $tmp_name = Input::file('file')->getRealPath();
            $file_name = Input::file('file')->getClientOriginalName();
            $file_type = Input::file('file')->getClientOriginalExtension();
////        }
//        exit;
        $reader = Excel::load($tmp_name);
        $count= $reader->getSheetCount();
//        $results = $reader->toArray();

//        Excel::load($_FILES["file"]["tmp_name"], function($reader) {
//
//            // Getting all results
//            $results = $reader->get();
//
//            // ->all() is a wrapper for ->get() and will work the same
//            $results = $reader->all();
//            var_dump($results->items);
//        });

        $xls_array = array();
        for($i = 0;$i<$count;$i++) {
            if($reader->getSheet($i)){
                $xls_array[$i]= $reader->getSheet($i)->toArray();
            }
        }
        $file_content = serialize($xls_array);
//        exit;
        require app_path().'/Lib/qiniu/rs.php';
        require app_path().'/Lib/qiniu/io.php';
        $file_path = $this->uploadfile($_FILES["file"]["name"],$_FILES["file"]["tmp_name"]);

        DB::beginTransaction();

        $file = new File();
        $file->file_name = $file_name;
//        $file->content = $file_content;
        $file->uploaded_by = Auth::user()->id;
        $file->key = $file_path;
        $file->save();


        $source = new Source();
        $source->contents = $file_content;
        $source->type = Input::get('type');
        $source->user_id = Auth::user()->id;
        $source->file_id = $file->id;
        $source->create_time = time();
        $source->create_date = date('Ymd');
        $source->save();
        DB::commit();

    }
    public function uploadfile($name,$tmp){
//        $type=array("jpg","gif","bmp","jpeg","png");//设置允许上传文件的类型
//
//        if(!in_array(strtolower($this->fileext($name)),$type))
//        {
//            $text=implode(",",$type);
//            echo "您只能上传以下类型文件: ",$text,"<br>";
//        }
//        //生成目标文件的文件名
//        else{
            $filename=explode(".",$name);
            $filename[0]=$this->random(10); //设置随机数长度
            $uploadfile=implode(".",$filename);
            //$name1=$name.".Mcncc";

            $result = $this->upPicTo7niu($tmp,'com',$uploadfile,'budao');
            return $result['key'];
//        }
    }


    /**
     *上传图片至七牛云
     *$path 图片地址
     *$dirname 在七牛云上的文类名称
     *$filename 文件保存名称
     *$bucket 你的七牛云域名称
     */
    function upPicTo7niu($path,$dirname,$filename,$bucket){

        $pub = Pub::find(1);
        $contents = @file_get_contents($path);

        $storename = $dirname."/".$filename;
        $bu = $bucket.":".$storename;
        $accessKey = $pub->qiniu_accessKey;
        $secretKey = $pub->qiniu_secretKey;

        Qiniu_SetKeys($accessKey, $secretKey);
        $putPolicy = new \Qiniu_RS_PutPolicy($bu);
        $upToken = $putPolicy->Token(null);
        $putExtra = new \Qiniu_PutExtra();
        $putExtra->Crc32 = 1;
        list($ret, $err) = Qiniu_Put($upToken, $storename, $contents, $putExtra);
        return $ret;
    }
    function random($length)
    {
        $hash = 'CR-';
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $max = strlen($chars) - 1;
        mt_srand((double)microtime() * 1000000);
        for($i = 0; $i < $length; $i++)
        {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

}
